package com.livedoc.ui.common.components;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.authroles.authentication.AuthenticatedWebSession;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.GenericPanel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.springframework.security.core.GrantedAuthority;

import com.livedoc.security.SecurityUserDetails;
import com.livedoc.ui.administration.AdministrationPage;
import com.livedoc.ui.application.LoginPage;

public class HeaderPanel extends GenericPanel<SecurityUserDetails> {

    private static final long serialVersionUID = 891726251828753954L;

    private static final String ROLE_ADMIN = "ROLE_ADMIN";

    public HeaderPanel(String id, IModel<SecurityUserDetails> model) {
	super(id, model);
    }

    @Override
    public void onInitialize() {
	super.onInitialize();
	AjaxLink<Void> logoutLink = new AjaxLink<Void>("logout-link") {

	    private static final long serialVersionUID = 2473429138180754076L;

	    @Override
	    public void onClick(AjaxRequestTarget target) {
		AuthenticatedWebSession session = AuthenticatedWebSession.get();
		session.signOut();
		session.invalidate();
		setResponsePage(LoginPage.class);
	    }
	};
	add(logoutLink);

	AjaxLink<Void> adminLink = new AjaxLink<Void>("admin-link") {

	    private static final long serialVersionUID = 2473429138180754076L;

	    @Override
	    public void onClick(AjaxRequestTarget target) {
		setResponsePage(AdministrationPage.class);
	    }

	    @Override
	    public void onConfigure() {
		super.onConfigure();
		setVisible(isUserAdmin(HeaderPanel.this.getModelObject()));
	    }
	};
	add(adminLink);

	Label userLabel = new Label("user-label", new PropertyModel<String>(
		getModelObject().getUser(), "name"));
	add(userLabel);
    }

    private boolean isUserAdmin(SecurityUserDetails details) {
	for (GrantedAuthority authority : details.getAuthorities()) {
	    if (authority.getAuthority().equals(ROLE_ADMIN)) {
		return true;
	    }
	}
	return false;
    }
}
